<!-- RichTextEditor.vue -->
<template>
    <div class="rich-text-editor">
        <!-- 工具栏 -->
        <div class="toolbar">
            <button v-for="level in [1, 2, 3]" :key="'h' + level" :class="{ active: headingActive === level }"
                @click="setHeading(level)">
                H{{ level }}
            </button>

            <button :class="{ active: isFormatActive('bold') }" @click="execCommand('bold')">
                <b>B</b>
            </button>

            <button :class="{ active: isFormatActive('italic') }" @click="execCommand('italic')">
                <i>I</i>
            </button>

            <button :class="{ active: isFormatActive('insertUnorderedList') }"
                @click="execCommand('insertUnorderedList')">
                📝 UL
            </button>

            <button :class="{ active: isFormatActive('insertOrderedList') }" @click="execCommand('insertOrderedList')">
                🔢 OL
            </button>

            <input type="color" ref="colorPicker" @input="setColor" style="display: none" />
            <button @click="$refs.colorPicker.click()">
                🎨 颜色
            </button>
        </div>

        <!-- 编辑区 -->
        <div class="editor" contenteditable="true" ref="editor" @keydown="handleKeydown" @input="updateContent"
            @mouseup="updateButtonStates" @keyup="updateButtonStates" @focus="updateButtonStates"
            @click="updateButtonStates"></div>

        <!-- 预览 -->
        <div class="preview">
            <h4>HTML 内容预览：</h4>
            <pre>{{ htmlContent }}</pre>
        </div>
    </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue';

const editor = ref(null);
const colorPicker = ref(null);
const htmlContent = ref('');
const headingActive = ref(0); // 当前标题级别

// 执行命令
const execCommand = (command, value = null) => {
    document.execCommand(command, false, value);
    editor.value.focus();
    updateButtonStates();
    updateContent();
};

// 设置标题
const setHeading = (level) => {
    const tag = `<h${level}>`;
    document.execCommand('formatBlock', false, tag);
    updateButtonStates();
    updateContent();
};

// 设置颜色
const setColor = (e) => {
    document.execCommand('foreColor', false, e.target.value);
    updateButtonStates();
    updateContent();
};

// 判断当前格式是否激活（如加粗、斜体等）
const isFormatActive = (command) => {
    try {
        return document.queryCommandState(command);
    } catch (e) {
        return false;
    }
};

// 更新按钮高亮状态（包括标题）
const updateButtonStates = () => {
    nextTick(() => {
        // 更新加粗、斜体、列表等状态
        // document.queryCommandState 可检测大部分格式

        // 检查当前选区的块级标签（用于标题）
        const selection = window.getSelection();
        if (!selection.rangeCount) return;

        const range = selection.getRangeAt(0);
        let container = range.commonAncestorContainer;

        // 如果是文本节点，取父节点
        if (container.nodeType === 3) {
            container = container.parentNode;
        }

        const tagName = container.tagName ? container.tagName.toLowerCase() : '';

        if (['h1', 'h2', 'h3'].includes(tagName)) {
            headingActive.value = parseInt(tagName[1]);
        } else {
            // 检查祖先节点中是否有 heading
            let parent = container;
            let level = 0;
            while (parent && parent !== editor.value) {
                if (['H1', 'H2', 'H3'].includes(parent.tagName)) {
                    level = parseInt(parent.tagName[1]);
                    break;
                }
                parent = parent.parentNode;
            }
            headingActive.value = level;
        }
    });
};

// 更新内容
const updateContent = () => {
    nextTick(() => {
        htmlContent.value = editor.value.innerHTML;
    });
};

// 阻止默认回车行为（可选增强）
const handleKeydown = (e) => {
    if (e.key === 'Enter' && e.shiftKey) {
        // Shift+Enter 插入换行
        document.execCommand('insertLineBreak');
        e.preventDefault();
    }
};

// 初始化
onMounted(() => {
    editor.value.focus();
    updateButtonStates();
});
</script>

<style scoped>
.rich-text-editor {
    width: 700px;
    margin: 20px auto;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.toolbar {
    border: 1px solid #ccc;
    padding: 8px;
    background-color: #fbfbfb;
    border-radius: 6px 6px 0 0;
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}

.toolbar button {
    padding: 6px 10px;
    border: 1px solid #ddd;
    background: white;
    cursor: pointer;
    font-weight: 600;
    font-size: 14px;
    border-radius: 4px;
    transition: all 0.2s;
}

.toolbar button:hover {
    background-color: #f0f0f0;
    border-color: #aaa;
}

.toolbar button.active {
    background-color: #007cba;
    color: white;
    border-color: #007cba;
    box-shadow: 0 0 0 1px rgba(0, 124, 186, 0.3);
}

.editor {
    min-height: 200px;
    border: 1px solid #ccc;
    border-top: none;
    padding: 12px;
    background: white;
    outline: none;
    line-height: 1.6;
    border-radius: 0 0 6px 6px;
    overflow-y: auto;
}

.editor:focus {
    box-shadow: 0 0 0 2px rgba(0, 124, 186, 0.2);
}

.preview {
    margin-top: 15px;
    padding: 12px;
    border: 1px solid #eee;
    border-radius: 4px;
    background-color: #f9f9f9;
    font-size: 14px;
    color: #333;
}
</style>